package com.laiketui.admin.store.service.dubbo;

import com.laiketui.admin.store.api.ResourcesService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.mapper.CustomerModelMapper;
import com.laiketui.common.mapper.FilesRecordModelMapper;
import com.laiketui.common.mapper.MchModelMapper;
import com.laiketui.common.mapper.UploadConfigModelMapper;
import com.laiketui.common.utils.tool.DateUtil;
import com.laiketui.common.utils.tool.ImgUploadUtils;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.str.StringUtils;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.log.AdminRecordModel;
import com.laiketui.domain.mch.AdminModel;
import com.laiketui.domain.mch.MchModel;
import com.laiketui.domain.upload.UploadConfigModel;
import com.laiketui.domain.upload.UploadImagModel;
import com.laiketui.domain.vo.MainVo;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 资源管理
 *
 * @author Trick
 * @date 2021/7/21 16:43
 */
@Service
public class ResourcesServiceImpl implements ResourcesService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FilesRecordModelMapper filesRecordModelMapper;

    @Autowired
    private UploadConfigModelMapper uploadConfigModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CustomerModelMapper customerModelMapper;

    @Autowired
    private MchModelMapper mchModelMapper;

    @Override
    public Map<String, Object> index(MainVo vo, String imageName, String startTime, String endTime) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", vo.getStoreId());
            if (StringUtils.isNotEmpty(imageName)) {
                parmaMap.put("imageName", imageName);
            }
            if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)){
                parmaMap.put("startTime", startTime);
                parmaMap.put("endTime", endTime);
            }
            //oos + minio
            List<String> uploadList = Arrays.asList(GloabConst.UploadConfigConst.IMG_UPLOAD_OSS, GloabConst.UploadConfigConst.IMG_UPLOAD_MINIO);
            parmaMap.put("add_time_sort", DataUtils.Sort.DESC.toString());
            parmaMap.put("uploadList",uploadList);
            parmaMap.put("pageStart", vo.getPageNo());
            parmaMap.put("pageEnd", vo.getPageSize());
            //获取自营店id
            Integer storeMchId = customerModelMapper.getStoreMchId(vo.getStoreId());
            MchModel mchModel = mchModelMapper.selectByPrimaryKey(storeMchId);
            int total = filesRecordModelMapper.countDynamic(parmaMap);
            List<Map<String, Object>> list = new ArrayList<>();
            if (total > 0) {
                list = filesRecordModelMapper.selectDynamic(parmaMap);
                for (Map<String, Object> map : list) {
                    map.put("imgUrl", publiceService.getImgPath(MapUtils.getString(map, "image_name"), vo.getStoreId()));
                    map.put("add_time", DateUtil.dateFormate(MapUtils.getString(map, "add_time"), GloabConst.TimePattern.YMDHMS));
                    if (StringUtils.isEmpty(MapUtils.getString(map, "mchName"))){
                        //默认为自营店上传
                        map.put("mchName", mchModel.getName());
                    }
                }
            }

            resultMap.put("total", total);
            resultMap.put("list", list);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("资源列表 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "index");
        }
        return resultMap;
    }

    @Override
    public void downForZip(MainVo vo, HttpServletResponse response, String imgIds) throws LaiKeAPIException {
        try {
            if (StringUtils.isEmpty(imgIds)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            List<Map<String, Object>> imgNameMaps = filesRecordModelMapper.getImgNameByIds(Arrays.asList(imgIds.split(SplitUtils.DH)));
            if (imgNameMaps == null || imgNameMaps.size() < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TPBCZ, "图片不存在");
            }

            UploadImagModel imagModel = new UploadImagModel();
            imagModel.setUploadType(GloabConst.UploadConfigConst.IMG_UPLOAD_OSS);
            //从数据库获取上传配置key
            UploadConfigModel uploadConfigModel = new UploadConfigModel();
            uploadConfigModel.setUpserver(imagModel.getUploadType());
            List<UploadConfigModel> uploadConfigs = uploadConfigModelMapper.select(uploadConfigModel);
            //装载参数
            imagModel.setUploadConfigs(uploadConfigs);

            //下载文件
            ImgUploadUtils file = new ImgUploadUtils();
            file.downImages(imagModel, imgNameMaps, response, vo.getStoreId(), vo.getStoreType());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("批量下载图片 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "downForZip");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(MainVo vo, String imgIds) throws LaiKeAPIException {
        try {
            AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            int row;
            List<String> ids = DataUtils.convertToList(imgIds.split(SplitUtils.DH));
            if (ids == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            for (String id : ids) {
                row = filesRecordModelMapper.deleteByPrimaryKey(id);
                if (row < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSB, "删除失败");
                }
            }
            publiceService.addAdminRecord(vo.getStoreId(),"将图片资源进行了批量删除操作", AdminRecordModel.Type.DEL, vo.getAccessId());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("批量删除 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "del");
        }
    }


}

